package leecode;

/**
 * @Classname
 * @Description TODO
 * @Date 2021/8/4 12:40
 * @Created by Alberthch
 * 题目：最长公共子序列
 */
class Solution_1143 {
    public static int[][] longestCommonSubsequence(String text1, String text2) {
        int m = text1.length();
        int n = text2.length();
        int[][] c= new int[m+1][n+1];
        for (int i = 0; i < m+1; i++) {
            c[i][0] = 0;
        }

        for (int j = 0; j < n+1; j++) {
            c[0][j] = 0;
        }

        for (int i = 1; i < m+1; i++) {
            for (int j = 1; j < n+1; j++) {
                if (text1.charAt(i-1) == text2.charAt(j-1)) {
                    c[i][j] = c[i-1][j-1] + 1;

                } else {
                    c[i][j] = Math.max(c[i-1][j],c[i][j-1]);
                }
            }

        }

        for (int i = 0; i < m+1; i++) {

        }
        return c;
    }

    public static void printLCS(int[][] c,String text1,int i,int j) {
        if(i == 0 || j == 0) {
            return;
        }
        if (c[i][j] == c[i-1][j-1] + 1) {
            printLCS(c,text1,i-1,j-1);
            System.out.print(text1.charAt(i-1));
        } else if (c[i][j] == c[i-1][j]) {
            printLCS(c,text1,i-1,j);
        } else {
            printLCS(c,text1,i,j-1);
        }
    }

    public static void main(String[] args) {
        String s = "ABCBDAB";
        String t = "BDCABA";
        int[][] res = longestCommonSubsequence(s,t);
        System.out.println(res[s.length()][t.length()]);

        // 打印最长公共子序列
        printLCS(res,s,s.length(),t.length());
    }
}
